/*
 * @Author: mikey.zhaopeng 
 * @Date: 2018-12-16 09:31:42 
 * @Last Modified by: mikey.zhaopeng
 * @Last Modified time: 2018-12-26 23:20:25
 */
import 'package:http/http.dart' as http;
import 'dart:convert';
import 'package:intl/intl.dart';

import 'package:flutter/material.dart';
import '../widgets//search_bar.dart';
import './search_page.dart';
import '../widgets/app_drawer.dart' show AppDrawer;
import '../widgets/Home_banner.dart' show HomeBanner;
import '../widgets/section_title.dart' show SectionTitle;
import '../widgets/today_boardcast.dart' show TodaysBoardcast;

import '../modles/tv_schedule.dart';

class HomePage extends StatefulWidget {
  @override
  _HomePageState createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  bool isLoading = true;
  final String drawerUrl =
      'http://ios.zmzapi.com/index.php?accesskey=519f9cab85c8059d17544947k361a827&client=1&g=api/v3&m=index&a=login&account=popeyelau%40gmail.com&did=2A2B9DE8-5038-4FBE-8ECB-DD86D3301FB1&password=Yyets123456&registration_id=141fe1da9efde137552';
  final String adsUrl = "http://ctrl.zmzapi.net/app/ads?platform=7&ver=252";

  Map profile;
  List ads;
  List<TVSchedule> schedeleList =[];
  @override
  void initState() {
    super.initState();
    getDrawer();
    getAds();
    getSchedule();
  }

//获取侧边栏数据
  void getDrawer() async {
    var response = await http.get(drawerUrl);
    Map map = json.decode(response.body)['data'];
    setState(() {
      profile = map;
    });
  }

//获取banner数据
  void getAds() async {
    var response = await http.get(adsUrl);
    List map = json.decode(response.body)['ads'];
    if (map.length > 0) {
      map.removeWhere((item) => item['pic'] == null);
      setState(() {
        ads = map;
        isLoading = false;
      });
    }
  }

//获取今日播放电视数据
  void getSchedule() async {
    final today = DateTime.now();
    final formatter = DateFormat("yyyy-MM-dd");
    final start = formatter.format(today);
    final end = formatter.format(today.add(Duration(days: 1)));
    final url =
        "http://ios.zmzapi.com/index.php?accesskey=519f9cab85c8059d17544947k361a827&client=1&g=api/v3&m=index&a=tv_schedule&end=$end&start=$start";
    List<TVSchedule> list = [];
    var response = await http.get(url);
    Map<String, dynamic> map = json.decode(response.body)['data'];
    map.keys.forEach((key) {
      list.addAll(
          (map[key] as List).map((v) => TVSchedule.fromJson(v)).toList());
    });
    setState(() {
      schedeleList = list;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      drawer: AppDrawer(
        profile: profile,
      ),
      appBar: AppBar(
        elevation: 0,
        title: GestureDetector(
          child: SearchBar(
            enabled: false,
          ),
          onTap: () {
            Navigator.of(context)
                .push(MaterialPageRoute(builder: (context) => SearchPage()));
          },
        ),
        actions: <Widget>[
          Container(
            margin: const EdgeInsets.only(right: 8.0, left: 8.0),
            child: CircleAvatar(
              child: Text(DateTime.now().day.toString()),
            ),
          ),
        ],
      ),
      body: Container(
        child: isLoading
            ? Center(
                child: CircularProgressIndicator(),
              )
            : Container(
                child: ListView(
                  primary: true,
                  children: <Widget>[
                    Padding(
                      padding: const EdgeInsets.all(8.0),
                      child: ads.isNotEmpty
                          ? HomeBanner(banners: ads)
                          : Container(),
                    ),
                    SectionTitle(
                      title: "今日播出",
                    ),
                    Padding(
                      padding: const EdgeInsets.symmetric(horizontal: 8.0),
                      child: schedeleList.isNotEmpty
                        ?TodaysBoardcast(schedules: schedeleList):Container(),
                    ),
                  ],
                ),
              ),
      ),
    );
  }
}
